import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Popconfirm,Radio,Table } from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './Users.less';

import DescriptionList from '../../components/DescriptionList';
import _ from 'lodash';
const { Description } = DescriptionList;

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['关闭', '运行中', '已上线', '异常'];
const identityMap = ['manager', 'user', 'guest'];
const identity = ['管理员', '用户', '游客'];

//新建记录的表单
const CreateForm = Form.create()((props) => {
  const { modalVisible, form, handleAdd, handleModalVisible } = props;
  //新建时的确定按钮function
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      message.info('This is a normal message');
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      title="新建规则"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false, "modalVisible")}
    >
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="描述"
      >
        {form.getFieldDecorator('desc', {
          rules: [{ required: true, message: 'Please input some description...' }],
        })(
          <Input placeholder="请输入" />
          )}
      </FormItem>
    </Modal>
  );
});
//代码重复了
const InfoModal = (props) => {
  const { modalVisible, form, handleAdd, handleModalVisible, description } = props;
  const okHandle = () => {
    message.info('This is a normal message');
  };
  //新建时的确定按钮function
  return (
    <Modal
      title="信息"
      visible={modalVisible}
      onCancel={() => handleModalVisible(false, "infoModalVisible")}
    >
      <DescriptionList className={styles.headerList} size="small" col="2">
        {_.map(description, ({ property, term, value }) => (
          <Description key={property} term={term}>{value}</Description>
        ))}
      </DescriptionList>
    </Modal>
  );
};
const StatusModal = (props) => {
  const { modalVisible, form, handleAdd, handleModalVisible, description } = props;
  //新建时的确定按钮function
  const okHandle = () => {
    message.info('This is a normal message');
  };
  return (
    <Modal
      title="信息"
      visible={modalVisible}
      onCancel={() => handleModalVisible(false, "statusModalVisible")}
    >
      <DescriptionList className={styles.headerList} size="small" col="2">
        {_.map(description, ({ property, term, value }) => (
          <Description key={property} term={term}>{value}</Description>
        ))}
      </DescriptionList>
    </Modal>
  );
};
//编辑记录的表单@connect(({ profile,loading }) => ({
const CreateEditForm = Form.create()((props) => {
  const { modalVisible, form, handleAdd, handleModalVisible,submitting } = props;
  const { getFieldDecorator, getFieldValue } = form;
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 7 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 },
      md: { span: 10 },
    },
  };

  const submitFormLayout = {
    wrapperCol: {
      xs: { span: 24, offset: 0 },
      sm: { span: 10, offset: 7 },
    },
  };

  //新建时的确定按钮function
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      message.info('This is a normal message');
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      console.log(values)
      if (!err) {
        message.info('提交成功');
      }
    });
  }
  return (
    <Modal
      title="新建规则"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false, "editModalVisible")}
    >
      <Form
        onSubmit={handleSubmit}
        hideRequiredMark
        style={{ marginTop: 8 }}
      >
        <FormItem
          {...formItemLayout}
          label="昵称"
        >
          {getFieldDecorator('petName', {
            rules: [{
              required: true, message: '不能为空',
            }],
          })(
            <Input placeholder="起个名字吧" />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="家乡"
        >
          {getFieldDecorator('hometown', {
            rules: [{
              required: true, message: '不能为空',
            }],
          })(
            <Input placeholder="出生的地方" />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="职业"
        >
          {getFieldDecorator('profession', {
            rules: [{
              required: true, message: '不能为空',
            }],
          })(
            <Input placeholder="请选择自己的职业" />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="个性签名"
        >
          {getFieldDecorator('resume', {
            rules: [{
              required: true, message: '不能为空',
            }],
          })(
            <TextArea style={{ minHeight: 32 }} placeholder="请多多介绍自己吧" rows={4} />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="性别"
          help=""
        >
          <div>
            {getFieldDecorator('gender', {
              rules: [{
                required: true, message: '不能为空',
              }],
            })(
              <Radio.Group>
                <Radio value="1">男</Radio>
                <Radio value="2">女</Radio>
                <Radio value="3">保密</Radio>
              </Radio.Group>
              )}
          </div>
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="生日"
        >
          {getFieldDecorator('birthday', {
            rules: [{
              required: true, message: '不能为空',
            }],
          })(
            <DatePicker style={{ width: '100%' }} placeholder="选择出生的那天吧" />
            )}
        </FormItem>
        <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
          <Button type="primary" htmlType="submit" loading={submitting}>
            提交
          </Button>
          <Button style={{ marginLeft: 8 }}>保存</Button>
        </FormItem>
      </Form>
    </Modal>
  );
});
  const expandedRowRender = () => {
    const columns = [
      { title: 'Date', dataIndex: 'date', key: 'date' },
      { title: 'Name', dataIndex: 'name', key: 'name' },
      { title: 'Status', key: 'state', render: () => <span><Badge status="success" />Finished</span> },
      { title: 'Upgrade Status', dataIndex: 'upgradeNum', key: 'upgradeNum' },
      {
        title: 'Action',
        dataIndex: 'operation',
        key: 'operation',
        render: () => (
          <span className="table-operation">
            <a href="#">Pause</a>
            <a href="#">Stop</a>
          </span>
        ),
      },
    ];

    const data = [];
    for (let i = 0; i < 3; ++i) {
      data.push({
        key: i,
        date: '2014-12-24 23:12:00',
        name: 'This is production name',
        upgradeNum: 'Upgraded: 56',
      });
    }
    return (
      <Table
        columns={columns}
        dataSource={data}
        pagination={false}
      />
    );
  };
@connect(({ profile, rule, loading }) => ({
  profile,
  rule,
  loading: loading.models.rule,
  submitting: loading.effects['profile/submitRegularForm'],
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    infoModalVisible: false,
    statusModalVisible: false,
    editModalVisible: false,
    expandForm: false,
    selectedRows: [],
    //查询时的表单参数
    formValues: {},
    description: [
      { property: 'name', term: "名字" },
      { property: 'petName', term: "昵称", value: '' },
      { property: 'gender', term: "性别", value: '' },
      { property: 'birthday', term: "生日", value: '' },
      { property: 'location', term: "所在地", value: '' },
      { property: 'hometown', term: "家乡", value: '' },
      { property: 'resume', term: "个性签名", value: '' },
      { property: 'profession', term: "职业", value: '' },
    ]
  };
  columns = [
    {
      title: '规则编号',
      dataIndex: 'no',
      sorter: true,
    },
    {
      title: '名字',
      dataIndex: 'description',
    },
    {
      title: '角色',
      dataIndex: 'callNo',
      filters: [
        {
          text: identity[0],
          value: 0,
        },
        {
          text: identity[1],
          value: 1,
        },
        {
          text: identity[2],
          value: 2,
        },
      ],
      render(val) {
        return <Badge status={identityMap[val]} text={identity[val]} />;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      filters: [
        {
          text: status[0],
          value: 0,
        },
        {
          text: status[1],
          value: 1,
        },
        {
          text: status[2],
          value: 2,
        },
        {
          text: status[3],
          value: 3,
        },
      ],
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '上线时间',
      dataIndex: 'updatedAt',
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      render: (text, record) => {
        const { disabled } = record;
        return (
          <div>
            {
              !disabled ?
                <Fragment>
                  <a onClick={() => this.handleModalVisible(true, "infoModalVisible")}>个人信息</a>
                  <Divider type="vertical" />
                  <a onClick={() => this.handleModalVisible(true, "editModalVisible")}>编辑</a>
                  <Divider type="vertical" />
                  <Popconfirm title="确定删除次记录(此操作是不可逆的)?" onConfirm={() => this.onDelete(record.key)}>
                    <a>删除</a>
                  </Popconfirm>
                </Fragment>
                : <span>无法操作</span>
            }
          </div>
        )
      }
    },
  ];



  deleting = () => {
    this.setState({ deleting: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        deleting: false,
      });
      message.info('记录删除成功');
    }, 1000);
  }
  onDelete = (key) => {
    const { dispatch } = this.props;
    const result = [...key];
    dispatch({
      type: 'rule/remove',
      payload: {
        no: key.toString(),
      },
      callback: () => {
        { message.info(key) }
        { message.info('删除成功') }
      },
    });
  }
  //加载数据
  componentDidMount() {
    const { dispatch, profile } = this.props;
    dispatch({
      type: 'rule/fetch',
    });
    dispatch({
      type: 'profile/fetchCurrentUserInfo',
    });
    for (let i = 0; i < this.state.description.length; i++) {
      this.state.description[i].value = profile.info[this.state.description[i].property]
    }
    console.log(this.state.description);
  }
  //处理
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'rule/fetch',
      payload: params,
    });
  }
  //重新从后台进行请求数据
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'rule/fetch',
      payload: {},
    });
  }
  //是否显示所有查询表单
  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  }

  handleMenuClick = (e) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'rule/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  }
  //将所有选中的列存储到state中
  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  }
  //查询操作
  handleSearch = (e) => {
    //阻止默认操作
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      //保存查询表单的查询参数
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'rule/fetch',
        payload: values,
      });
    });
  }
  //显示Modal
  handleModalVisible = (flag, value) => {
    message.info(value)
    this.setState({
      [value]: !!flag,
    });
  }
  //添加记录
  handleAdd = (fields) => {
    this.props.dispatch({
      type: 'rule/add',
      payload: {
        description: fields.desc,
      },
    });

    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
  }
  //上方的查询 表单
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="规则编号">
              {getFieldDecorator('no')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                  <Option value="2">已上线</Option>
                  <Option value="3">异常</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  //上方的查询 表单展开后的
  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="规则编号">
              {getFieldDecorator('no')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                  <Option value="2">已上线</Option>
                  <Option value="3">异常</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="调用次数">
              {getFieldDecorator('number')(
                <InputNumber style={{ width: '100%' }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="上线日期">
              {getFieldDecorator('updatedAt')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入上线日期" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="角色">
              {getFieldDecorator('status3')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">管理员</Option>
                  <Option value="1">用户</Option>
                  <Option value="2">游客</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status4')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">查询</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </span>
        </div>
      </Form>
    );
  }
  //判断是否展开的显示
  renderForm() {
    return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { rule: { data }, loading,submitting } = this.props;
    const { selectedRows, editModalVisible, modalVisible, statusModalVisible, infoModalVisible, description } = this.state;
    //和[更多操作]绑定了
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      description: description,
      submitting:submitting,
    };
    return (
      <PageHeaderLayout title="用户管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderForm()}
            </div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true, "modalVisible")}>
                新建
              </Button>
              {
                selectedRows.length > 0 && (
                  <span>

                    <Dropdown overlay={menu}>
                      <Button>
                        批量操作 <Icon type="down" />
                      </Button>
                    </Dropdown>
                  </span>
                )
              }
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
        />
        <CreateEditForm
          {...parentMethods}
          modalVisible={editModalVisible}
        />
        <StatusModal
          {...parentMethods}
          modalVisible={statusModalVisible}
        />
        <InfoModal
          {...parentMethods}
          modalVisible={infoModalVisible}
        />
      </PageHeaderLayout>
    );
  }
}
